package org.jeecg.modules.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.mes.entity.MesProductionTemplate;
import org.jeecg.modules.mes.entity.MesTemplateWorkType;
import org.jeecg.modules.mes.mapper.MesProductionTemplateMapper;
import org.jeecg.modules.mes.mapper.MesTemplateWorkTypeMapper;
import org.jeecg.modules.mes.service.IMesProductionTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

/**
 * @Description: 生产计划模板
 * @Author: jeecg-boot
 * @Date: 2025-01-21
 * @Version: V1.0
 */
@Service
public class MesProductionTemplateServiceImpl extends ServiceImpl<MesProductionTemplateMapper, MesProductionTemplate> implements IMesProductionTemplateService {

    @Resource
    private MesTemplateWorkTypeMapper templateWorkTypeMapper;

    @Override
    public boolean checkTemplateCodeExists(String templateCode, String excludeId) {
        return baseMapper.checkTemplateCodeExists(templateCode, excludeId) > 0;
    }

    @Override
    public MesProductionTemplate getDefaultTemplate() {
        return baseMapper.getDefaultTemplate();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> setDefaultTemplate(String templateId) {
        try {
            // 检查模板是否存在
            MesProductionTemplate template = this.getById(templateId);
            if (template == null) {
                return Result.error("模板不存在");
            }

            // 设置默认模板
            baseMapper.setDefaultTemplate(templateId);
            
            return Result.ok("设置默认模板成功");
        } catch (Exception e) {
            log.error("设置默认模板失败", e);
            return Result.error("设置默认模板失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> saveTemplateWithWorkTypes(Map<String, Object> templateData) {
        try {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            
            // 保存模板基本信息
            MesProductionTemplate template = new MesProductionTemplate();
            template.setTemplateCode((String) templateData.get("templateCode"));
            template.setTemplateName((String) templateData.get("templateName"));
            template.setDescription((String) templateData.get("description"));
            template.setIsDefault(Integer.valueOf( templateData.get("isDefault").toString()));
            template.setStatus(Integer.valueOf( templateData.get("status").toString()));
            template.setRemark((String) templateData.get("remark"));

            String templateId = (String) templateData.get("id");
            if (oConvertUtils.isNotEmpty(templateId)) {
                // 更新模板
                template.setId(templateId);
                template.setUpdateBy(loginUser.getUsername());
                template.setUpdateTime(new Date());
                this.updateById(template);
                
                // 删除原有工种配置
                templateWorkTypeMapper.deleteByTemplateId(templateId);
            } else {
                // 新增模板
                template.setCreateBy(loginUser.getUsername());
                template.setCreateTime(new Date());
                this.save(template);
                templateId = template.getId();
            }

            // 保存工种配置
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> workTypeList = (List<Map<String, Object>>) templateData.get("workTypes");
            if (workTypeList != null && !workTypeList.isEmpty()) {
                List<MesTemplateWorkType> templateWorkTypes = new ArrayList<>();
                for (Map<String, Object> workTypeData : workTypeList) {
                    MesTemplateWorkType templateWorkType = new MesTemplateWorkType();
                    // 生成ID - 修复 "Column 'id' cannot be null" 错误
                    String generatedId = String.valueOf(IdWorker.getId());
                    templateWorkType.setId(generatedId);
                    templateWorkType.setTemplateId(templateId);
                    templateWorkType.setWorkTypeId((String) workTypeData.get("workTypeId"));
                    templateWorkType.setWorkTypeCode((String) workTypeData.get("workTypeCode"));
                    templateWorkType.setWorkTypeName((String) workTypeData.get("workTypeName"));
                    // 安全的类型转换处理
                    Object sequenceObj = workTypeData.get("sequence");
                    templateWorkType.setSequence(sequenceObj != null ? Integer.valueOf(sequenceObj.toString()) : null);

                    
                    Object isRequiredObj = workTypeData.getOrDefault("isRequired", 0);
                    templateWorkType.setIsRequired(isRequiredObj != null ? Integer.valueOf(isRequiredObj.toString()) : 0);
                    templateWorkType.setRemark((String) workTypeData.get("remark"));
                    templateWorkType.setCreateBy(loginUser.getUsername());
                    templateWorkType.setCreateTime(new Date());
                    templateWorkType.setSysOrgCode(loginUser.getOrgCode());
                    
                    templateWorkTypes.add(templateWorkType);
                }
                
                if (!templateWorkTypes.isEmpty()) {
                    // 改用单个插入，避免批量插入的ID问题
                    for (MesTemplateWorkType workType : templateWorkTypes) {
                        templateWorkTypeMapper.insert(workType);
                    }
                }
            }

            // 如果设置为默认模板，需要清除其他默认标识
            if (template.getIsDefault() == 1) {
                baseMapper.setDefaultTemplate(templateId);
            }

            return Result.ok("保存模板成功");
        } catch (Exception e) {
            log.error("保存模板失败", e);
            return Result.error("保存模板失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getTemplateWithWorkTypes(String templateId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取模板基本信息
        MesProductionTemplate template = this.getById(templateId);
        if (template != null) {
            result.put("template", template);
            
            // 获取工种配置
            List<MesTemplateWorkType> workTypes = templateWorkTypeMapper.getWorkTypesByTemplateId(templateId);
            result.put("workTypes", workTypes);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteTemplateWithWorkTypes(String templateId) {
        try {
            // 检查是否为默认模板
            MesProductionTemplate template = this.getById(templateId);
            if (template != null && template.getIsDefault() == 1) {
                return Result.error("不能删除默认模板");
            }

            // 删除工种配置
            templateWorkTypeMapper.deleteByTemplateId(templateId);
            
            // 删除模板
            this.removeById(templateId);
            
            return Result.ok("删除模板成功");
        } catch (Exception e) {
            log.error("删除模板失败", e);
            return Result.error("删除模板失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> copyTemplate(String sourceTemplateId, String newTemplateName) {
        try {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            
            // 获取源模板信息
            Map<String, Object> sourceData = this.getTemplateWithWorkTypes(sourceTemplateId);
            MesProductionTemplate sourceTemplate = (MesProductionTemplate) sourceData.get("template");
            if (sourceTemplate == null) {
                return Result.error("源模板不存在");
            }

            // 创建新模板
            MesProductionTemplate newTemplate = new MesProductionTemplate();
            newTemplate.setTemplateCode(sourceTemplate.getTemplateCode() + "_COPY");
            newTemplate.setTemplateName(newTemplateName);
            newTemplate.setDescription("复制自：" + sourceTemplate.getTemplateName());
            newTemplate.setIsDefault(0); // 复制的模板不设为默认
            newTemplate.setStatus(1);
            newTemplate.setRemark(sourceTemplate.getRemark());
            newTemplate.setCreateBy(loginUser.getUsername());
            newTemplate.setCreateTime(new Date());
            this.save(newTemplate);

            // 复制工种配置
            @SuppressWarnings("unchecked")
            List<MesTemplateWorkType> sourceWorkTypes = (List<MesTemplateWorkType>) sourceData.get("workTypes");
            if (sourceWorkTypes != null && !sourceWorkTypes.isEmpty()) {
                List<MesTemplateWorkType> newWorkTypes = new ArrayList<>();
                for (MesTemplateWorkType sourceWorkType : sourceWorkTypes) {
                    MesTemplateWorkType newWorkType = new MesTemplateWorkType();
                    newWorkType.setTemplateId(newTemplate.getId());
                    newWorkType.setWorkTypeId(sourceWorkType.getWorkTypeId());
                    newWorkType.setWorkTypeCode(sourceWorkType.getWorkTypeCode());
                    newWorkType.setWorkTypeName(sourceWorkType.getWorkTypeName());
                    newWorkType.setSequence(sourceWorkType.getSequence());
                    newWorkType.setIsRequired(sourceWorkType.getIsRequired());
                    newWorkType.setRemark(sourceWorkType.getRemark());
                    newWorkType.setCreateBy(loginUser.getUsername());
                    newWorkType.setCreateTime(new Date());
                    newWorkType.setSysOrgCode(loginUser.getOrgCode());
                    
                    newWorkTypes.add(newWorkType);
                }
                
                templateWorkTypeMapper.batchInsert(newWorkTypes);
            }

            return Result.ok("复制模板成功");
        } catch (Exception e) {
            log.error("复制模板失败", e);
            return Result.error("复制模板失败：" + e.getMessage());
        }
    }

    @Override
    public List<?> getTemplateWorkTypes(String templateId) {
        try {
            QueryWrapper<MesTemplateWorkType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("template_id", templateId);
            queryWrapper.eq("del_flag", 0);
            queryWrapper.orderByAsc("sequence");
            
            List<MesTemplateWorkType> workTypes = templateWorkTypeMapper.selectList(queryWrapper);
            return workTypes;
        } catch (Exception e) {
            log.error("获取模板工种配置失败", e);
            return new ArrayList<>();
        }
    }
}
